import { defineStore } from 'pinia'
import { useUserApi } from "@/api/user";
import {IUserLogin} from "@/types/login";

// 初始化状态
const userInfoState: {userInfo: IUserLogin} = {
  userInfo: {
    authorities: [],
    displayName: '',
    email: '',
    expired: 0,
    id: '',
    instId: '',
    instName: '',
    name: '',
    passwordSetType: 0,
    refresh_token: '',
    remeberMe: '',
    ticket: '',
    token: '',
    twoFactor: '',
    type: '',
    username: '',
  }
}

export const USER_INFO = 'userInfo';

export const useUserStore = defineStore('user',
  {
    state: (): {userInfo: IUserLogin} => ({
      ...userInfoState
    }),
    actions: {
      // 设置用户信息
      setUserInfo(val: IUserLogin) {
        this.userInfo = val;
      },
      setUserAvatar(avatar: string) {
        console.log('设置用户头像', avatar)
        console.log('userInfo', this.$state)
      },
      // 删除用户信息
      removeUserInfo() {
        this.$state = { ...userInfoState }
        uni.removeStorageSync('userInfo')
      },
      /**
       * 获取用户信息
       */
      async getUserInfo() {
        const res = await useUserApi().getUserInfo()
        const userInfo = res.data
        this.setUserInfo(userInfo)
        uni.setStorageSync('userInfo', userInfo)
        // TODO 这里可以增加获取用户路由的方法 根据用户的角色动态生成路由
        return res
      },
      getStateUserInfo() {
        return this.userInfo;
      }
    },
    persist: true,
  },
)
